package com.small.os.minio.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.small.os.minio.entity.AqUpload;
import com.small.os.minio.entity.vo.AqUploadCompose;
import com.small.os.minio.entity.vo.AqUploadInit;
import com.small.os.minio.entity.vo.MinioQ;
import com.small.os.minio.enums.AqUploadStartEnum;
import com.small.os.minio.mapper.AqUploadMapper;
import com.small.os.minio.service.IAqUploadService;
import com.small.os.minio.util.MinIoUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangguochao
 * @since 2020-10-20
 */
@Service
public class AqUploadServiceImpl extends ServiceImpl<AqUploadMapper, AqUpload> implements IAqUploadService {


    /**
     * 1、系统里有完成的，
     * 2、系统里有未完成的
     * 3、
     */
    @Override
    public Map<String, Object> uploadFilesInPieces(AqUploadInit param) {
        String fileName = param.getFileName();
        int lastIndexOf = fileName.lastIndexOf(".");
        String prefix = fileName.substring(0, lastIndexOf);
        String suffix = fileName.substring(lastIndexOf);
        int i = this.countByMd5(param.getFileMd5());
        AqUpload aqUpload = new AqUpload();
        BeanUtils.copyProperties(param, aqUpload);
        aqUpload.setSuffix(suffix);
        aqUpload.setPrefix(prefix);
        aqUpload.setUploadStatus(AqUploadStartEnum.UPLOAD_SUCCESS);
        //有完成的
        if (i > 0) {
            this.createAFile(aqUpload);
            Map<String, Object> map = new HashMap<>();
            map.put("UPLOAD_SUCCESS", 1);
            return map;
        } else {
            //无完成的
            return this.secondUpload(aqUpload);
        }
    }

    /**
     * 1、根据md5获取上传部分的的片段
     * 2、获取文件名
     * 3、如果有同名文件+（1）
     * 4、合并文件到指定位置
     */
    @Override
    public boolean composeFile(AqUploadCompose param) {
        //自定义文件名称
        String fileName = param.getFileName();
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf);
        String prefix = fileName.substring(0, lastIndexOf);
        //根据md5获取所有分片文件名称(minio的文件名称 = 文件path)
        List<String> chunks = MinIoUtils.listObjectNames("chunk", param.getFileMd5());
        //合并文件
        if (MinIoUtils.composeObject(chunks, param.getFileMd5() + suffix)) {
            AqUpload aqUpload = new AqUpload();
            BeanUtils.copyProperties(param, aqUpload);
            aqUpload.setSuffix(suffix);
            aqUpload.setPrefix(prefix);
            aqUpload.setUploadStatus(AqUploadStartEnum.UPLOAD_SUCCESS);
            this.createAFile(aqUpload);
            return true;
        }
        return false;
    }

    /**
     * 创建文件
     */
    private void createAFile(AqUpload aqUpload) {
        //根据md5获取所有分片文件名称(minio的文件名称 = 文件path)
//        1、同文件不同名
//        2、同名不同文件
        int ms = this.countByMd5(aqUpload.getFileMd5(), aqUpload.getParentIds());
        int fs = this.countByFileName(aqUpload.getFileName(), aqUpload.getParentIds());
        String fileName = aqUpload.getFileName();
        if (fs > 0) {
            fileName = aqUpload.getPrefix() + "（" + fs + "）" + aqUpload.getSuffix();
        }
        if (ms == 0 || fs == 0) {
            aqUpload.setFileName(fileName);
            this.save(aqUpload);
        }
    }

    @Override
    public List<AqUpload> findByPath(String parentIds) {
        LambdaQueryWrapper<AqUpload> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(parentIds != null, AqUpload::getParentIds, parentIds)
                .eq(parentIds == null, AqUpload::getParentIds, "TOP")
                .eq(AqUpload::getUploadStatus, AqUploadStartEnum.UPLOAD_SUCCESS)
                .orderByDesc(AqUpload::getIsDir)
                .orderByAsc(AqUpload::getCreated);
        List<AqUpload> list = list(wrapper);
        for (AqUpload aqUpload : list) {
            String url = MinIoUtils.getObjectUrl(aqUpload.getFileMd5() + aqUpload.getSuffix(), 720);
            aqUpload.setFilePath(url);
        }
        return list;
    }


    @Override
    public boolean renameOrFolderColor(String id, String folderColor) {
        UpdateWrapper<AqUpload> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(AqUpload::getId, id)
                .set(folderColor != null, AqUpload::getFolderColor, folderColor);
        return this.update(wrapper);
    }

    @Override
    public long countByFileNameAndDir(String fileName, String parentIds) {
        LambdaQueryWrapper<AqUpload> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AqUpload::getFileName, fileName);
        wrapper.eq(parentIds != null, AqUpload::getParentIds, parentIds);
        wrapper.isNull(parentIds == null, AqUpload::getParentIds);
        return count(wrapper);
    }

    /**
     * 获取文件列-分页
     */
    @Override
    public IPage<AqUpload> pageByPath(MinioQ param) {
        LambdaQueryWrapper<AqUpload> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(param.getParentIds() != null,
                AqUpload::getParentIds, param.getParentIds())
                .like(param.getFileName() != null,
                        AqUpload::getFileName, param.getFileName())
                .eq(param.getCategories() != null,
                        AqUpload::getCategories, param.getCategories())
                .orderByDesc(AqUpload::getIsDir)
                .orderByAsc(AqUpload::getCreated);
        IPage<AqUpload> iPage = this.page(param.page(), wrapper);
        List<AqUpload> records = iPage.getRecords();
        for (AqUpload aqUpload : records) {
            String url = MinIoUtils.getObjectUrl(aqUpload.getFileMd5() + aqUpload.getSuffix(), 720);
            aqUpload.setFilePath(url);
        }
        return iPage;
    }


    public int countByMd5(String fileMd5) {
        LambdaQueryWrapper<AqUpload> query1 = Wrappers.lambdaQuery();
        query1.eq(AqUpload::getFileMd5, fileMd5)
                .eq(AqUpload::getUploadStatus, AqUploadStartEnum.UPLOAD_SUCCESS);
        return this.count(query1);
    }

    @Override
    public int countByMd5(String fileMd5, String parentIds) {
        LambdaQueryWrapper<AqUpload> query1 = Wrappers.lambdaQuery();
        query1.eq(AqUpload::getFileMd5, fileMd5)
                .eq(AqUpload::getParentIds, parentIds)
                .eq(AqUpload::getUploadStatus, AqUploadStartEnum.UPLOAD_SUCCESS);
        return this.count(query1);
    }

    @Override
    public int countByFileName(String fileName, String parentIds) {
        LambdaQueryWrapper<AqUpload> query1 = Wrappers.lambdaQuery();
        query1.eq(AqUpload::getFileName, fileName)
                .eq(AqUpload::getParentIds, parentIds)
                .eq(AqUpload::getUploadStatus, AqUploadStartEnum.UPLOAD_SUCCESS);
        return this.count(query1);
    }


    /**
     * 二次上传
     *
     * @return 结果
     */
    private Map<String, Object> secondUpload(AqUpload aqUpload) {
        Map<String, Object> map = new HashMap<>();
        //续传
        Map<Integer, String> okChunkMap = MinIoUtils.mapChunkObjectNames(null, aqUpload.getFileMd5());
        List<AqUpload> chunkUploadUrls = new ArrayList<>();
        if (okChunkMap == null || okChunkMap.size() > 0) {
            for (int i = 1; i <= aqUpload.getChunkCount(); i++) {
                //判断当前分片是否已经上传过了
                if (okChunkMap == null || !okChunkMap.containsKey(i)) {
                    //生成分片上传url
                    AqUpload url = new AqUpload();
                    url.setPartNumber(i);
                    url.setUploadUrl(MinIoUtils.createUploadChunkUrl(null, aqUpload.getFileMd5(), i));
                    chunkUploadUrls.add(url);
                }
            }
            //没有数据返回完成
            if (chunkUploadUrls.size() == 0) {
                this.createAFile(aqUpload);
                map.put("UPLOAD_SUCCESS", 1);
            } else {
                map.put("UPLOAD_SUCCESS", 0);
                map.put("mysqlFileData", chunkUploadUrls);
            }

        }

        return map;
    }
}
